package 力扣日常刷题.木23一月.第13天313;

/**
 * @author 帅小伙
 * @date 2022/3/13
 * @description
 */
public class Demo59单词搜索 {

    public boolean exist(char[][] board,String word) {
        int h = board.length,w = board[0].length;
        boolean[][] visited = new boolean[h][w];

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                boolean flag = check(board,visited,i,j,word,0);
                if(flag){
                    return true;
                }
            }
        }
        return false;
    }


    public boolean check(char[][] board, boolean[][] visited,int x,int y,String word,int index) {
        if(board[x][y] != word.charAt(index)){
            return false;
        }else if(index == word.length() - 1){
            return true;
        }

        visited[x][y] = true;
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        boolean result = false;

        for (int[] dir : directions) {
            int nx = x + dir[0],ny = y + dir[1];
            if(nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length) {
                if(!visited[nx][ny]) {
                    boolean flag = check(board,visited,nx,ny,word,index+1);
                    if(flag) {
                        result = true;
                        break;
                    }
                }
            }
        }
        visited[x][y] = false;
        return result;
    }
}
